<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Three.js Click and Focus with Animation Demo</title>
    <style>
        body { margin: 0; }
        canvas { display: block; }
    </style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/18.6.4/tween.umd.js"></script>
<script>
    let scene, camera, renderer;
    let raycaster, mouse;
    let focusTween;

    init();
    animate();

    function init() {
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        renderer = new THREE.WebGLRenderer();

        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2();

        // 创建一个立方体对象作为可点击的物体
        let geometry = new THREE.BoxGeometry();
        let material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
        let cube = new THREE.Mesh(geometry, material);
        cube.position.set(1, 0, 0);
        scene.add(cube);

        // 创建一个球体对象
        let sphereGeometry = new THREE.SphereGeometry(0.5, 32, 32);
        let sphereMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        let sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        scene.add(sphere);

        camera.position.z = 5;

        // 点击事件处理函数
        function onClick(event) {
            // 计算鼠标点击位置
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

            // 通过鼠标位置和相机投影矩阵计算射线
            raycaster.setFromCamera(mouse, camera);
            let intersects = raycaster.intersectObjects(scene.children);

            if (intersects.length > 0) {
                let obj = intersects[0].object;
                let objPos = obj.position;

                // 添加Tween动画，让相机平滑移动到目标位置
                focusTween = new TWEEN.Tween(camera.position)
                    .to({ x: objPos.x, y: objPos.y, z: objPos.z + 3 }, 1000)
                    .easing(TWEEN.Easing.Quadratic.Out)
                    .onUpdate(() => {
                        camera.lookAt(objPos);
                        camera.updateProjectionMatrix();
                    })
                    .start();

                console.log("Clicked on object:", obj);
            }
        }

        window.addEventListener('click', onClick, false);
    }

    function animate() {
        requestAnimationFrame(animate);
        TWEEN.update();
        renderer.render(scene, camera);
    }
</script>
</body>
</html>
